<?php
/**
 * Class representation of the HTML <input type="text" /> tag. It can be added to containers.
 *
 * @author Niels Janssen
 * @since 2008-07-08
 * @package Form.Elements
 */
class Checkbox extends FormContainer {

	private $checked = false;
	private $disable = false;

	/**
	 * Constructor for the TextField class, passes variables to the FormElement constructor.
	 *
	 * @param String $name
	 */
	public function __construct( $name, $label = '', $checked = false, $value = '', $class = '' )
	{
		$this->checked = $checked;

		parent::__construct( $name, array( 'value' => $value, 'label' => $label, 'checked' => $checked, 'class' => $class ) );
	}

	public function setName( $name ) {
		$this->name = $name;
	}

	public function isChecked() {
		return (bool) $this->checked;
	}
	
	public function getValue() {
		return $this->isChecked();
	}
	
	public function setValue( $checked ) {
		$this->setChecked( $checked );
	}
	
	public function isValid() {
		return $this->checked ? parent::isValid() : true;
	}

	public function setChecked( $checked ) {
		$this->checked = $checked;

		if( class_exists( 'CheckboxContainer' ) && $this->parent instanceof CheckboxContainer  )
			$this->parent->setChecked( $this );
	}

	public function check()
	{
		$this->setChecked(true);
		return $this;
	}

	public function uncheck()
	{
		$this->setChecked(false);
		return $this;
	}

	public function setParent( $container ) {
		parent::setParent( $container );
	}

	public function setDisabled( $disable ) {
		$this->disable = $disable;
	}

	/**
	 * @see FormElement::__toString()
	 */
	public function __toString() {
		$output =  '
			<div class="form checkbox">
				<label>
					<input type="checkbox" name="' . ( $this->getFormName() != '' ? $this->getFormName() . '_' : '' ) . $this->name . '" id="' . ( $this->getFormName() != '' ? $this->getFormName() . '_' : '' ) . $this->name . '" value="' . ( empty ( $this->value ) ? 'on' : $this->value ) . '"' . ( $this->checked ? ' checked="checked"' : '' ) . ( $this->disable ? ' disabled="disabled"' : '' ) . ' class="' . $this->getProperty('class') . '" />
				' . $this->getProperty("label") . ( $this->inAJAXMode() || !empty( $this->errorMessage ) ? '<div class="error' . ( $this->inAJAXMode() ? ' ajax' : '' ) . '" id="' . ( $this->getFormName() != '' ? $this->getFormName() . '_' : '' ) . $this->name . '_error">' . $this->errorMessage . '</div>' : '' ) . '
				';

		if( $this->hasChildren( ) )
		{
			$output .= '<div class="checkboxelements" id="checkboxelements_' . $this->name . '">';

			foreach( $this->children as $child ) {
				$output .= $child;
			}

			$output .= '</div>';
		}

		$output .= '
				</label>
				</div>';

		return $output;
	}
}

?>